<?php
class Auction_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
        $this->load->database();
    }
    //获取当天竞拍商品信息
    function getGoodsArray(){
        //今日竞拍商品
        $todayGoods = $this->get_auctiongoods_by_date(date("Y-m-d"));
        //今日竞拍商品的各种信息     
        foreach ($todayGoods as $key=>$item){
            //出价前5出价数据
            $todayGoods[$key]['auctionOffers'] = $this->get5thAuction($item['id']); 
            //出价次数
            $todayGoods[$key]['auctionOffersTime']= $this->getAGtime($item['id']);
            //我的出价历史
            $todayGoods[$key]['auctionOffersSelf'] = $this->getMyAuction($item['id']);
        }
        //明日竞拍商品
        //$tomorrowGoods = $this->get_auctiongoods_by_date(date("Y-m-d"));
        $tomorrowGoods = array();
        return array($todayGoods,$tomorrowGoods);
    }
    //竞拍商品的前5出价
    function get5thAuction($agid){
        $this->db->select("`id`,`agid`,`openid`,`auctionTime`,`offer`,`nickname`,`figureurl`,if(UNIX_TIMESTAMP()-`auctionTime`>60,if(UNIX_TIMESTAMP()-`auctionTime`>3600,concat(floor((UNIX_TIMESTAMP()-`auctionTime`)/3600),'时前'),concat(floor((UNIX_TIMESTAMP()-`auctionTime`)/60),'分前')),concat(UNIX_TIMESTAMP()-`auctionTime`,'秒前'))  shicha",FALSE);
        $this->db->where(array('agid' => $agid , 'openid !=' => 'B593C4B6B36B97C3CE6848BE662B938E'));
        $this->db->order_by("`auctionTime` DESC");
        $query = $this->db->get("auctiontoday",5);
        return $query->result_array();
    }
    //竞拍商品的出价次数
    function getAGtime($agid){
        $this->db->select("count(`id`) cid");
        $this->db->where(array('agid' => $agid, "openid !="=>"B593C4B6B36B97C3CE6848BE662B938E",));
        $query = $this->db->get("auctiontoday",1);
        $getAGtime = $query->row_array();
        return $getAGtime['cid'];
    }
    //竞拍商品的 我的出价历史
    function getMyAuction($agid){
        $this->db->select("`offer`,if(UNIX_TIMESTAMP()-`auctionTime`>60,if(UNIX_TIMESTAMP()-`auctionTime`>3600,concat(floor((UNIX_TIMESTAMP()-`auctionTime`)/3600),'时前'),concat(floor((UNIX_TIMESTAMP()-`auctionTime`)/60),'分前')),concat(UNIX_TIMESTAMP()-`auctionTime`,'秒前')) shicha", FALSE);
        $this->db->where(array('agid' => $agid , 'openid' => $this->session->userdata('openid')));
        $this->db->order_by("`auctionTime` DESC");
        $query = $this->db->get("auctiontoday");
        return $query->result_array();
    }
    //获取竞拍商品信息
    function get_auctiongoods_by_date($date){
    	$this->db->select("id,url,name,pic,pirce");
    	$query = $this->db->get_where('auctiongoods', array('pDate'=>$date,'status'=>1 ,'isDel'=>0), 3);
    	return $query->result_array();
    }
    //轮播中奖的名单、中奖统计、用户是否中奖
    function getauctionSuc(){
        //前20个中奖用户
        $this->db->select("aid,name,nickname,figureurl,pirce,openid");
        $this->db->where("auctionDate <" , date("Y-m-d"));
        $this->db->order_by("auctionDate DESC ,agid ASC");
        $query = $this->db->get("auctionsuccess",20);
        $rs['list'] = $query->result_array();
        //中奖统计
        $this->db->select("COUNT(`id`) cid,SUM(`pirce`) sp",FALSE);
        $this->db->where("auctionDate <",date("Y-m-d"));
        $query = $this->db->get("auctionsuccess",1);
        $rs['statis'] = $query->row_array();
        //用户中奖数
        $this->db->select("COUNT(`id`) cid",FALSE);
        $this->db->where(array("openid"=>$this->session->userdata('openid'),"isreceive !="=> 1 , "isInvalid !="=> 1 , "isExceedTheTimeLimit !=" => 1));
        $query = $this->db->get("auctionsuccess",1);
        $rs['countUserAward'] = $query->row_array();
        return $rs;
    }
    //竞价
    function AjaxUserOffer($id,$offer,$ip,$userInfo){
    	$openid = $this->session->userdata('openid')?$this->session->userdata('openid'):"error";//$openid
    	$openid = strval($openid);
    	if ($openid=="error" || $openid===0) {
    		return array("ret"=>-200,"msg"=>"请重新登录");
    	}
    	
        $user = $userInfo['web'];
        /* ---商品--- */
        $this->db->select("id");
        $this->db->where(array("pDate"=>date("Y-m-d"),"id"=>$id));
        $query = $this->db->get("auctiongoods");
        $goodsNum = $query->num_rows(); //商品数量
        if ($goodsNum<=0) {
        	return array('ret'=>-4,'msg'=>'商品过期或不存在！');//商品过期或不存在
        }
        /* ---出价--- */
        $this->db->select("offer");
        $this->db->where(array("openid"=>$openid,"agid"=>$id));
        $query = $this->db->get("auctiontoday");
        $offer_by_goodsid = $query->result_array(); //这件商品的出价明细
        $offertime = $query->num_rows(); //出价次数
        //出价次数限制20
        if ($offertime>=20) {
        	return array('ret'=>-2,'msg'=>'每个商品最多出价20次！'); //每个商品最多出价20次
        }
        //有出价
        if ($offertime>0) {
            //出价明细
            foreach ($offer_by_goodsid as $item){
            	$offerArray[] = $item['offer'];
            }
            if (in_array($offer, $offerArray)) {
            	return array('ret'=>-3,'msg'=>'已出过这个价格！'); //出价不重复
            }
        }
        //金币判断
        if (($user['GoldCoinNumber']-10)<0) {
        	return array('ret'=>-5,'msg'=>'金币不足！'); //金币不过
        }
        //黑名单
        /* $this->db->where("openid",$this->session->userdata('openid'));
        $query = $this->db->get("auctionblacklist");
        $blackListNum = $query->num_rows(); */
        //if ($blackListNum>0) {
        if (1==2) {
        	$data = array(
        		"agid"=>$id,
        	    "openid"=>"B593C4B6B36B97C3CE6848BE662B938E",
        	    "auctionDate"=>date("Y-m-d"),
        	    "auctionTime"=>time(),
        	    "offer"=>$offer,
        	    "nickname"=>"/ty普通的猫",
        	    "gender"=>"男",
        	    "city"=>"厦门",
        	    "ip"=>$ip
        	);
        	$this->db->insert('auction', $data);//插入虚拟数据
        }
        /*------------------------------插入数据-----------------------------*/
        $data = array(
        	"agid"   =>$id,
        	"openid" =>$this->session->userdata('openid'),
        	"auctionDate" =>date("Y-m-d"),
        	"auctionTime" =>time(),
        	"offer"     =>$offer,
            "nickname"  =>$userInfo['tx']['nickname'],
       		"figureurl" =>$userInfo["tx"]["figureurl"],
            "gender" =>$userInfo['tx']['gender']?$userInfo['tx']['gender']:"男",
            "city"   =>$userInfo['tx']['city'],
            "ip"     =>$ip
        );
        $this->db->insert('auction', $data);//插入数据
        //修改数量 金钱
        $this->db->set("GoldCoinNumber","GoldCoinNumber-10",FALSE);
        $this->db->where("Identifier",$openid);
        $this->db->update("users");
        //金币操作记录
        $data = array(
        		'openid' => strval($openid),
        		'gold'   => -10,
        		'gold_old' => $user['GoldCoinNumber'],
        		'gold_new' => $user['GoldCoinNumber']-10,
        		'action' => '竞拍',
        		'time'   => date('Y-m-d H:i:s')
        );
        $this->db->insert('users_gold_add',$data);
        //历史竞拍
        $rs['historyOffer'] = $this->get5thAuction($id);
        //我的竞拍
        $rs['selfOffer']  = $this->getMyAuction($id);
        //总竞拍数量
        $rs['totalOffer'] = $this->getAGtime($id);
        //ret=1
        $rs['ret'] = 1;
        return $rs;
    }
    //------------------------------兑换商品-----------------------------//
    //获取当天兑换商品信息
    function getExchangeGoods($date=''){
    	$date = $date?$date:date("Y-m-d");
    	$this->db->select("id,url,name,pic,pirce,exchangeNum,exchangeGold,exchangeNumTol,guanzhu");
    	$this->db->select("if( HOUR(NOW())>=10,if(`exchangeNum`>0,1,0),-1) `isUse`",false);
    	$query = $this->db->get_where('zz_extend_exchangegoods', array('pDate'=>$date,'status'=>1 ,'isDel'=>0), 3);
    	return $query->result_array();
    }
    //预设兑换时出现的问题
    function setExchangeQuestion(){
    	$this->db->query("CALL setExchangeQuestion(@status)");
    }
    //获取兑换问题
    function AjaxExchange($id,$status){
    	$date = date("Y-m-d");
    	//集体兑换成功列表
    	$rs['exchangeList'] = $this->getExchangeGoodsList($id);
    	//判断是否有剩余
    	$isExchangeGoods = $this->isExchangeGoods($id,"pwd,exchangeNum,exchangeNumTol,exchangeGold");
    	//判断是否已经兑换成功
    	$isUserGetExchangeGoods = $this->isUserGetExchangeGoods($id);
    	if ($isUserGetExchangeGoods['num']) {
    		$rs = array_merge($rs,array('ret'=>2,'msg'=>'已经兑换成功！'));
    		$rs['pwd'] = $isUserGetExchangeGoods['pwd'];
    		$rs['num'] = $isExchangeGoods['exchangeNumTol'];
    		return $rs;
    	}
    	//兑换结束
    	if ($status==0) {
    		$rs['ret'] = 0;
    		$rs['num'] = $isExchangeGoods['exchangeNumTol'];
    		$rs['msg'] = "已经竞拍结束！";
    		return $rs;
    	}
    	//判断是否兑换结束
    	if ($isExchangeGoods['exchangeNum']>0) {
    		$this->db->select("question,answer");
	    	$this->db->where("turntime",$date);
	    	$query = $this->db->get("zz_extend_exchange_question",1);
	    	$num = $query->num_rows();
	    	if ($num) {//问题存在
	    		$rs['num'] = $isExchangeGoods['exchangeNumTol'];
	    		$rs['question'] = $query->row_array();
	    		$rs['ret'] = 1;
	    	}else{//问题不存在
	    		$rs['ret'] = -2;
	    		$rs['msg'] = "问题不存在，系统错误";
	    	}
    	}else{
    		$rs['ret'] = 0;
    		$rs['num'] = $isExchangeGoods['exchangeNumTol'];
    		$rs['msg'] = "已经竞拍结束！";
    	}
    	return $rs;
    }
    //开始兑换
    function AjaxExchange2($id,$userinfo){
    	$openid = $this->session->userdata('openid')?$this->session->userdata('openid'):"error";//$openid
    	$openid = strval($openid);
    	if ($openid=="error" || $openid===0) {
    		return array("ret"=>-200,"msg"=>"请重新登录");
    	}
    	//判断是否已经兑换成功
    	$isUserGetExchangeGoods = $this->isUserGetExchangeGoods($id);
    	if ($isUserGetExchangeGoods['num']) {
    		$rs = array('ret'=>-100,'msg'=>'已经兑换成功！');
    		return $rs;
    	}
    	$isExchangeGoods = $this->isExchangeGoods($id,"*");
    	//判断是否竞拍结束
    	if ($isExchangeGoods['exchangeNum']<=0) {
    		//集体兑换成功列表
    		$rs['exchangeList'] = $this->getExchangeGoodsList($id);
    		//$rs['exchangeList'] = '';
    		return array_merge(array('ret'=>2,'msg'=>'已经兑换结束！'),$rs);
    	}
    	//-----还没结束-----//
    	//金币判断
    	$oldGold = $userinfo['web']['GoldCoinNumber'];
    	if (($oldGold-$isExchangeGoods['exchangeGold'])<0) {
    		return array('ret'=>0,'msg'=>'金币不足！'); //金币不过
    	}
    	//没有问题了
    	$rs = array();
    	//兑换
    	$this->db->query("CALL `userExchangeSuccess` ({$id},'{$openid}',@ret,@msg,@lastinsertid)");
    	$query = $this->db->query("SELECT @ret ret,@msg msg,@lastinsertid lastinsertid");
    	$rs = $query->row_array();
    	
    	$rs['num'] = $isExchangeGoods['exchangeNumTol'];//剩余次数
    	if ($rs['ret']==1) {//兑换成功
    		$pwd = $this->generate_password();
    		//更新数据
    		$data = array(
    			'pDate'     =>$isExchangeGoods['pDate'],
    			'pwd'       =>$pwd,
    			'name'      =>$isExchangeGoods['name'],
    			'pirce'     =>$isExchangeGoods['pirce'],
    			'pic'       =>$isExchangeGoods['pic'],
    			'url'       =>$isExchangeGoods['url'],
    			'exchangeGold' => $isExchangeGoods['exchangeGold'],
    			'nickname'  =>$userinfo['tx']['nickname'],
    			'figureurl' =>$userinfo["tx"]["figureurl"],
    			'gender'    =>$userinfo['tx']['gender']?$userinfo['tx']['gender']:"男",
    			'city'      =>$userinfo["tx"]["city"],
    			'oldgold'   =>$oldGold
    		);
    		$this->db->where('id',$rs['lastinsertid']);
    		$this->db->where('agid',$id);
    		$this->db->where('openid',$openid);
    		$this->db->update('zz_extend_exchange_success',$data);
    		//成功密码
    		$rs['pwd'] = $pwd;
    		$rs['userExchangeSucc'] = array(
    			'exchangeGold' => $isExchangeGoods['exchangeGold'],
    			'nickname'     => $userinfo['tx']['nickname'],
    			'figureurl'    => $userinfo["tx"]["figureurl"],
    			'gender'       => $userinfo['tx']['gender']?$userinfo['tx']['gender']:"男",
    			'city'         => $userinfo["tx"]["city"],
    			'auctionTime2' => date("Y年m月d日 H:i:s"),
    		);
    		//金币操作记录
    		$data = array(
    				'openid'   => strval($openid),
    				'gold'     => -$isExchangeGoods['pirce'],
    				'gold_old' => $oldGold,
    				'gold_new' => $oldGold-$isExchangeGoods['exchangeGold'],
    				'action' => '兑换',
    				'time'   => date('Y-m-d H:i:s')
    		);
    		$this->db->insert('users_gold_add',$data);
    	}
    	if($rs['ret']==2){
    		//集体兑换成功列表
    		$rs['exchangeList'] = $this->getExchangeGoodsList($id);
    	}
    	return $rs;
    }
    //生成密码
    private function generate_password( $length = 8 ) {
    	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    	$password = '';
    	for ( $i = 0; $i < $length; $i++ ){
    		$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    	}
    	return trim($password);
    }
    //兑换商品
    function isExchangeGoods($id,$col="exchangeNum,exchangeGold"){
    	$date = date("Y-m-d");
    	//判断是否有剩余
    	$this->db->select($col);
    	$this->db->where("id",$id);
    	$this->db->where("pDate",$date);
    	$this->db->where(date("G")." >=",10,false);
    	$query = $this->db->get("zz_extend_exchangegoods");
    	$exchangeNumA = $query->row_array();
    	$exchangeNumA = count($exchangeNumA)>0?$exchangeNumA:array('exchangeNum'=>null,'exchangeGold'=>null);
    	return $exchangeNumA;
    }
    //用户是否已经兑换了商品
    function isUserGetExchangeGoods($id,$col="id,pwd",$date=null){
    	$openid = $this->session->userdata('openid');
    	$openid = strval($openid);
    	$date = $date?$date:date("Y-m-d");
    	$this->db->select($col);
    	$this->db->where("agid",$id);
    	$this->db->where('openid',$openid);
    	$this->db->where("auctionDate",$date);
    	$query = $this->db->get("zz_extend_exchange_success");
    	$num = $query->num_rows();
    	if ($num>0) {
    		$rs = $query->row_array();
    		return array_merge($rs,array('num'=>$num));
    	}else{
    		return array('num'=>0);
    	}
    }
    //商品集体兑换列表 by 商品id
    function getExchangeGoodsList($id,$date=NULL){
    	$date = $date?$date:date("Y-m-d");
    	$this->db->select("`figureurl`,`nickname`,`gender`,`city`,`exchangeGold`,FROM_UNIXTIME(`auctionTime`,'%Y年%m月%d日') `auctionTime1`,FROM_UNIXTIME(`auctionTime`,'%Y年%m月%d日 %H:%i:%s') `auctionTime2`",false);
    	$this->db->where("agid",$id);
    	$this->db->where("auctionDate",$date);
    	$query = $this->db->get("zz_extend_exchange_success");
    	return $query->result_array();
    }
    /* ----------------------------------------------------------------------------------------
     * ----------------------------------------免费竞拍历史----------------------------------------
     * ---------------------------------------------------------------------------------------- */
    //1.1竞拍成功     处理 添加
    function auctionsuccess(){
    	$yesterday = date("Y-m-d",strtotime("-1 day"));
    	//昨天竞拍成功数$num
    	$this->db->select("id");
    	$this->db->where("auctionDate",$yesterday);
    	$query = $this->db->get("auctionsuccess");
    	$num = $query->num_rows();
    	//昨天竞拍商品$num2
    	$this->db->select("id");
    	$this->db->where("pDate",$yesterday);
    	$query = $this->db->get("auctiongoods");
    	$num2 = $query->num_rows();
    	if ($num!=$num2) {
    		//1.竞拍虚拟用户设定，及出价
    		$yesterdayGoodsid = $query->result_array();
    		$a_s_users = $this->auctionUserAndOffer($yesterdayGoodsid);
    		//call useroffer(5,1300,'FB0F7ED55396A66E8E32A3117D75B8EC','小鱼','http://thirdapp3.qlogo.cn/qzopenapp/aff242e95d20fb90a8a16b158fd95c517a6688dd7f868e27155b11401a09d4fc/50','女','漳州','沈晓煜');
    		//2.删除记录
    		$this->db->where("auctionDate",$yesterday);
    		$this->db->delete("auctionsuccess");
    		//3.插入记录
    		$sql = "INSERT INTO auctionsuccess(agid,aid,pDate,pwd,`name`,pirce,pic,url,auctionDate,auctionTime,nickname,figureurl,gender,city,openid,offer) ".
    				"SELECT ag.id agid, a.id aid, ag.pDate, ag.pwd, ag.name, ag.pirce,ag.pic,ag.url,a.auctionDate,a.auctionTime,a.nickname,a.figureurl,a.gender,a.city,a.openid,a.offer FROM auction a LEFT JOIN auctiongoods ag ON a.agid = ag.id ".
    				"WHERE a.id IN (SELECT id FROM (SELECT id,offer FROM (SELECT id,agid,auctionDate,offer,count(id) FROM auction WHERE auctionDate = DATE_SUB(CURDATE(), INTERVAL 1 day) GROUP BY agid,auctionDate,offer HAVING count(id)=1) a1 GROUP BY agid,auctionDate HAVING offer = MIN(offer)) a2) ";
    		$this->db->query($sql);
    		//4.插入记录2
    		$sql = "UPDATE auctionsuccess a1 SET offertimes = (SELECT COUNT(id) FROM auction a2 WHERE a2.agid=a1.agid AND a2.auctionDate=a1.auctionDate) WHERE offertimes IS NULL";
    		$this->db->query($sql);
    		//5.竞拍详情
    		$sql = "SELECT id,aid FROM auctionsuccess WHERE auctionDate = DATE_SUB(CURDATE(), INTERVAL 1 day)";
    		$query = $this->db->query($sql);
    		$zuorijingpai = $query->result_array();
    		foreach ($zuorijingpai as $key=>$item){
    			$data = $this->auctionInfo($item['aid'], 2);
    			$offerdetail = json_encode($data['auction_s']);
    			$sql = "UPDATE auctionsuccess a1 SET offerdetail = '{$offerdetail}' WHERE id = {$item['id']}";
    			$this->db->query($sql);
    		}
    		/* //6.今日竞拍用户更改
    		$this->db->select("id");
    		$this->db->where("auctionDate",$yesterday);
    		$query = $this->db->get("auctionsuccess",3);
    		$a_s_ids = $query->result_array();
    		for ($i=0;$i<=2;$i++){
    			$sql = "UPDATE `auctionsuccess` SET `nickname` = '{$a_s_users[$i]['nickname']}',`figureurl` = '{$a_s_users[$i]['figureurl']}',`gender` = '{$a_s_users[$i]['gender']}',`city` = '{$a_s_users[$i]['city']}',`openid` = 'cyy make user {$i}' WHERE id = {$a_s_ids[$i]['id']}";
    			$this->db->query($sql);
    		} */
    	}
    }
    //1.2具体竞拍信息
    function auctionInfo($aid,$type){
    	$sql="SELECT agid,aid,pDate,`name`,pirce,pic,url,auctionDate,auctionTime,nickname,figureurl,gender,city,openid,offer,DATE_FORMAT(FROM_UNIXTIME(auctionTime),'%H 时 %i 分 %s 秒') atime,offerdetail FROM auctionsuccess WHERE aid={$aid}";
		$query = $this->db->query($sql);
    	$rs['auction']=$query->row_array();
    	if(empty($rs['auction']['offerdetail'])){
    		$sql="SELECT * FROM (".
    				"(SELECT offer,COUNT(id) cid,0 islowest FROM auction WHERE auctionDate = '{$rs['auction']['auctionDate']}' AND agid = {$rs['auction']['agid']} AND offer<{$rs['auction']['offer']} GROUP BY offer ORDER BY offer DESC LIMIT 15 ) UNION ".
    				"(SELECT {$rs['auction']['offer']},1,1) UNION".
    				"(SELECT offer,COUNT(id) cid,0 FROM auction WHERE auctionDate = '{$rs['auction']['auctionDate']}' AND agid = {$rs['auction']['agid']} AND offer>{$rs['auction']['offer']} GROUP BY offer ORDER BY offer ASC LIMIT 14 )".
    				") tb1 ORDER BY tb1.offer ASC";
    		$query = $this->db->query($sql);
    		$rs['auction_s']=$query->result_array();
    	}else {
    		$rs['auction_s'] = json_decode($rs['auction']['offerdetail'],TRUE);
    	}
    	return $rs;
    }
    //1.2竞拍虚拟用户设定，及出价
    function auctionUserAndOffer($yesterdayGoodsid=null){
    	
    	//1.设定
    	$this->db->query("CALL setAuctionSuccUser(@status)");
    	
    	$this->db->where("turntime",date("Y-m-d"));
    	$query = $this->db->get("auctionsuccessuser");
    	 $users = $query->result_array();
    	//2.出价
    	//var_dump($users,"<br/>===",$yesterdayGoodsid);
    	
    	//出价
    	/* for($i=0;$i<=2;$i++){
    		$this->db->query("call useroffer2(5,{$yesterdayGoodsid[$i]['id']},'cyy make user{$i}','{$users[$i]['nickname']}','{$users[$i]['figureurl']}','{$users[$i]['gender']}','{$users[$i]['city']}','cyy make ip{$i}');");
    	} */
    	
    	return $users;
    	//exit();
    	//call useroffer(5,1300,'FB0F7ED55396A66E8E32A3117D75B8EC','小鱼','http://thirdapp3.qlogo.cn/qzopenapp/aff242e95d20fb90a8a16b158fd95c517a6688dd7f868e27155b11401a09d4fc/50','女','漳州','沈晓煜');
    }
    //2.历史数据
    function auctionHistory(){
    	$auctionSucc = $this->auctionSuccGoods();//竞拍
    	$exchangeSucc = $this->exchangeSuccGoods();//兑换
    	//历史数据整理
    	$TenDayAgoData2 = array();
    	foreach ($auctionSucc['TenDayAgoData'] as $item){
    		for ($i=1;$i<=10;$i++){
    			$date = date("Y-m-d",strtotime("-".$i." day"));
    			if($date == $item['auctionDate']){
    				if($date == $item['auctionDate']){
    					$item['price'] = (float)$item['pirce'];
    					$TenDayAgoData2[$date]["auctionSucc"][]=$item;
    					$TenDayAgoData2[$date]["auctionDate"]  =date("m 月 d 日",strtotime($date));
    					break;
    				}
    			}
    		}
    	}
    	foreach ($exchangeSucc['TenDayAgoData'] as $item){
    		for ($i=1;$i<=10;$i++){
    			$date = date("Y-m-d",strtotime("-".$i." day"));
    			if($date == $item['pDate']){
    				$item['price'] = (float)$item['pirce'];
    				$TenDayAgoData2[$date]["exchangeSucc"][]=$item;
    				$TenDayAgoData2[$date]["exchangeDate"]  =date("m 月 d 日",strtotime($date));
    				break;
    			}
    			 
    		}
    	}
    	//排序
    	$TenDayAgoData3 = array();
    	for ($i=1;$i<=10;$i++){
    		$date = date("Y-m-d",strtotime("-".$i." day"));
    		
    		$TenDayAgoData3[$date]["auctionSucc"]  = isset($TenDayAgoData2[$date]["auctionSucc"])?$TenDayAgoData2[$date]["auctionSucc"]:NULL;
    		$TenDayAgoData3[$date]["auctionDate"]  = isset($TenDayAgoData2[$date]["auctionDate"])?$TenDayAgoData2[$date]["auctionDate"]:NULL;
    		$TenDayAgoData3[$date]["exchangeSucc"] = isset($TenDayAgoData2[$date]["exchangeSucc"])?$TenDayAgoData2[$date]["exchangeSucc"]:NULL;
    		$TenDayAgoData3[$date]["exchangeDate"] = isset($TenDayAgoData2[$date]["exchangeDate"])?$TenDayAgoData2[$date]["exchangeDate"]:NULL;
    	
    	}
    	return array('exchangeself'=>$exchangeSucc['selfAGs'],'auctionself'=>$auctionSucc['selfAGs'],'TenDayAgoData'=>$TenDayAgoData3);
    }
    //2.1竞拍历史页面
    function auctionSuccGoods(){
    	//个人获奖历史 SELECT * FROM auctionsuccess WHERE auctionDate<'".date("Y-m-d")."' AND openid = '{$_SESSION['openid']}' ORDER BY auctionDate DESC ,agid ASC
    	$this->db->select("id,agid,aid,name,pirce,pic,url,nickname,isreceive,auctionTime,isInvalid,isExceedTheTimeLimit");
    	$this->db->where("auctionDate <",date("Y-m-d"));
    	$this->db->where("openid",$this->session->userdata('openid'));
    	$this->db->order_by("auctionDate DESC ,agid ASC");
    	$query = $this->db->get("auctionsuccess");
    	$selfAGs = $query->result_array();
    	//历史获奖 SELECT * FROM auctionsuccess WHERE auctionDate = '{$item['auctionDate']}' ORDER BY auctionDate DESC ,agid ASC
    	$date = date("Y-m-d",strtotime("-10 day"));
    	$this->db->select("id,agid,aid,name,pirce,pic,url,nickname,auctionDate");
    	$this->db->where("auctionDate <",date("Y-m-d"));
    	$this->db->where("auctionDate >=",$date);
    	$this->db->order_by("auctionDate DESC ,agid ASC");
    	$query = $this->db->get("auctionsuccess");
    	$TenDayAgoData = $query->result_array();
    	
    	return array("selfAGs"=>$selfAGs,"TenDayAgoData"=>$TenDayAgoData);
    }
    //2.2兑换历史页面
    function exchangeSuccGoods(){
    	$date = date("Y-m-d",strtotime("-10 day"));
    	//个人中奖
    	$this->db->select("id,agid,name,pirce,pic,url,auctionTime,auctionDate,exchangeGold,isreceive,isInvalid,isExceedTheTimeLimit");
    	$this->db->where("auctionDate <=",date("Y-m-d"));
    	$this->db->where("openid",$this->session->userdata('openid'));
    	$this->db->order_by("auctionDate DESC ,agid ASC");
    	$query = $this->db->get("zz_extend_exchange_success");
    	$selfAGs = $query->result_array();
    	//兑换的商品
    	$this->db->select("id,pDate,name,pirce,pic,url,exchangeGold");
    	$this->db->where("pDate <",date("Y-m-d"));
    	$this->db->where("pDate >=",$date);
    	$this->db->order_by("pDate DESC ,id ASC");
    	$query = $this->db->get("zz_extend_exchangegoods");
    	$exchangeSucc = $query->result_array();
    	 
    	return array("selfAGs"=>$selfAGs,"TenDayAgoData"=>$exchangeSucc);
    }
    //3.竞拍出价详情
    function AjaxAuctionSuccInfo($id,$type=1){//type：1没密码，2有密码
    	//获奖用户信息
    	$openid = $this->session->userdata('openid');
    	$openid = strval($openid);
    	if ($type==2) {
    		$this->db->select("pwd");
    		$this->db->where("openid",$openid);
    	}
    	$this->db->select("id,agid,aid,name,pirce,pic,url,nickname,figureurl,gender,city,auctionTime,offer,offerdetail");
    	$this->db->where("auctionDate <",date("Y-m-d"));
    	$this->db->where("id",$id);
    	$query = $this->db->get("auctionsuccess");
    	$AuctionSuccInfo = $query->row_array();
    	$AuctionSuccInfo['auctionTime'] = date("H时i分s秒",$AuctionSuccInfo['auctionTime']);
    	//出价历史
    	$AuctionSuccInfo['offerdetail'] = json_decode($AuctionSuccInfo['offerdetail'],true);
    	return $AuctionSuccInfo;
    }
    
    //4.兑换详情
    function AjaxExchangeSuccInfo($id,$date){
    	$exchangeSucc = $this->getExchangeGoodsList($id,$date);
    	$num = sizeof($exchangeSucc);
    	return array("ret"=>1,"data"=>$exchangeSucc,"num"=>$num);
    }
    //5.个人兑换密码
    function AjaxUserExchangeSuccInfo($id,$date){
    	//个人密码
    	$self = $this->isUserGetExchangeGoods($id,"id,pwd,url",$date);
    	//集体兑换详情
    	$exchangeSucc = $this->getExchangeGoodsList($id,$date);
    	$num = sizeof($exchangeSucc);
    	return array("ret"=>1,"data"=>$exchangeSucc,"num"=>$num,"self"=>$self);
    }
    //6.兑换的问题
    function AjaxExchangeQuestion(){
    	$this->db->select("question,answer");
    	$this->db->where("turntime",date("Y-m-d"));
    	$query = $this->db->get("zz_extend_exchange_question",1);
    	$num = $query->num_rows();
    	if ($num) {//问题存在
    		//$rs['num'] = $isExchangeGoods['exchangeNum'];
    		$rs['question'] = $query->row_array();
    		$rs['ret'] = 1;
    	}else{//问题不存在
    		$rs['ret'] = -2;
    		$rs['msg'] = "问题不存在，系统错误";
    	}
    	return $rs;
    }
}